#! /usr/bin/env python
# -*- coding=utf-8 -*-
import sys
import os
import re
from ircbot import SingleServerIRCBot
from irclib import nm_to_n, nm_to_h, irc_lower, ip_numstr_to_quad, ip_quad_to_numstr, parse_nick_modes

class AngelBot(SingleServerIRCBot):
    def __init__(self, channel, nickname, server, port=6667):
        SingleServerIRCBot.__init__(self, [(server, port)], nickname, nickname)
        self.channel = channel
	self.password = "PASSWORD"
	self.admin_token = "PASSWORD"

    def on_nicknameinuse(self, c, e):
        c.nick(c.get_nickname() + "_")

    def is_admin(self, nick):
    	admin_list = [
		"afang",
		"ghosTM55"
	]
	if nick in admin_list:
		return True
	return False

    def on_welcome(self, c, e):
    	c.privmsg("NickServ", "identify " + self.password)
        c.join(self.channel)
	c.privmsg("ChanServ", "op " + self.channel)

    def on_privmsg(self, c, e):
        #self.do_command(e, e.arguments()[0])
	text = e.arguments()[0].decode("utf-8")
	nick = nm_to_n(e.source())
	
	re_kick = re.compile(u"^kick\s(?P<badguy>\w+).*token=(?P<token>\w+).*")
	result = re_kick.match(text)
	if result:
		badguy = result.group("badguy").encode("utf-8")
		if self.is_admin(nick) and result.group("token") == self.admin_token:
			test_pre = " 使用超级无敌猪猪猪把坏人 "
			test_post = " 哄出聊天室. 聊天室从此恢复了平静."
			c.kick(self.channel, badguy, comment=c.get_nickname() + test_pre + badguy + test_post)

    def on_pubmsg(self, c, e):
	#        a = e.arguments()[0].split(":", 1)
	#        if len(a) > 1 and irc_lower(a[0]) == irc_lower(self.connection.get_nickname()):
	#            self.do_command(e, a[1].strip())
	#        return
	nickname = self.connection.get_nickname()

	#	The message to me
	re_tome = re.compile(u"^\s*" + nickname + "(\s|,|:)\s*(?P<content>.+)")
	result = re_tome.match(e.arguments()[0].decode("utf-8"))
	if result:
		content = result.group("content")
		
		#	For what question
		re_what_is_list = [
			u".*what\'(s|re)\s+(?P<the_object>[\w\s]+)\s*\?*",
			u".*what\s+(is|are)\s+(?P<the_object>[\w\s]+)\s*\?*",
			u".*(什么(东西)?|啥(子)?|何(物)?)(是|乃|为|叫做)\s*(?P<the_object>[\u4e00-\u9fa5\w]+)(啊|吗|吧)?\s*[\?\？]*",
			u"(请问|请教(一下)?|告诉(我|[大小]?爷|叔|哥|姐|姨|俺|小的))?(?P<the_object>[\u4e00-\u9fa5\w]+)(乃|是|为|叫做)(什么(东(西|东))?|啥(子)?|何(物)?)[\?\？]*"
		]
		for rule in re_what_is_list:
			re_what_is = re.compile(rule,re.I|re.U)
			result = re_what_is.match(content)
			if result:
				c.privmsg(e.target(), "You asked a \"what\" question about: " + result.group("the_object").encode("utf-8"))
				break
		
		#	For how question
		re_howto_list = [
			u".*how\s*(to|do\s+I)\s(?P<the_object>[\w\s]+\w)\s*\?*",
			u".*(如何|怎么|怎(么)?样)(去|才能)?(?P<the_object>[\u4e00-\u9fa5\w]+)(呢|啊|呀)?[\?\(？)]*"
		]
		for rule in re_howto_list:
			re_howto = re.compile(rule, re.I|re.U)
			result = re_howto.match(content)
			if result:
				c.privmsg(e.target(), "You asked a \"how\" question about: " + result.group("the_object").encode("utf-8"))
				break

		
		#	For can question
		re_can_list = [
			u".*(?P<can>(can|could|would|should))\s+(?P<subject>(I|we|you|he|she|us|it|they))\s+(?P<the_object>[\w\s]+\w)\s*\?*"
			#u".*(?P<can>(can|could|would|should))\s+(?P<subject>(I|we|you|he|she|us|it|they))\s+(P<the_object>[\w\s]+\w)\s*\?*"

		]
		for rule in re_can_list:
			re_can = re.compile(rule, re.I|re.U)
			result = re_can.match(content)
			if result:
				subject_list = {
					"i": "you",
					"you": "I",
					"we": "we",
					"he": "he",
					"she": "she",
					"us": "we",
					"it": "it",
					"they": "they"
				}
				c.privmsg(e.target(), "Yes, " + subject_list[result.group("subject").lower()] + " " + result.group("can").lower() + " .")
				break


    def on_dccmsg(self, c, e):
        c.privmsg("You said: " + e.arguments()[0])

    def on_dccchat(self, c, e):
        if len(e.arguments()) != 2:
            return
        args = e.arguments()[1].split()
        if len(args) == 4:
            try:
                address = ip_numstr_to_quad(args[2])
                port = int(args[3])
            except ValueError:
                return
            self.dcc_connect(address, port)

    def do_command(self, e, cmd):
        nick = nm_to_n(e.source())
        c = self.connection

        if cmd == "disconnect":
            self.disconnect()
        elif cmd == "die":
            self.die()
        elif cmd == "stats":
            for chname, chobj in self.channels.items():
                c.notice(nick, "--- Channel statistics ---")
                c.notice(nick, "Channel: " + chname)
                users = chobj.users()
                users.sort()
                c.notice(nick, "Users: " + ", ".join(users))
                opers = chobj.opers()
                opers.sort()
                c.notice(nick, "Opers: " + ", ".join(opers))
                voiced = chobj.voiced()
                voiced.sort()
                c.notice(nick, "Voiced: " + ", ".join(voiced))
        elif cmd == "dcc":
            dcc = self.dcc_listen()
            c.ctcp("DCC", nick, "CHAT chat %s %d" % (
                ip_quad_to_numstr(dcc.localaddress),
                dcc.localport))
        else:
            c.notice(nick, "Not understood: " + cmd)

def main():
    if len(sys.argv) != 4:
        print "Usage: testbot <server[:port]> <channel> <nickname>"
        sys.exit(1)

    s = sys.argv[1].split(":", 1)
    server = s[0]
    if len(s) == 2:
        try:
            port = int(s[1])
        except ValueError:
            print "Error: Erroneous port."
            sys.exit(1)
    else:
        port = 6667
    channel = sys.argv[2]
    nickname = sys.argv[3]

    bot = AngelBot(channel, nickname, server, port)
    bot.start()

if __name__ == "__main__":
    main()
